package cn.itcast.service.impl;

import cn.itcast.dao.MenuDao;
import cn.itcast.dao.PermissionDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Permission;
import cn.itcast.service.PermissionService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public PageResult findPermission(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Permission> page = permissionDao.findAllPermissionsByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void addPermission(Permission permission) {
        permissionDao.addPermission(permission);
    }

    @Override
    public void updatePermission(Permission permission) {
        permissionDao.updatePermission(permission);
    }

    @Override
    public Permission findPermissionById(Integer id) {
        return permissionDao.findPermissionById(id);
    }

    @Override
    public boolean deletePermissionById(Integer id) {
        //判断是否有外键关联
        if (permissionDao.findMenuCountByPermissionById(id)==0&&permissionDao.findRoleCountByPermissionById(id)==0) {
            return permissionDao.deletePermissionById(id)>0;
        }
        return false;
    }

    @Override
    public List<Permission> findAllPermission() {
        return permissionDao.findAllPermissionsByCondition(null);
    }

    @Override
    public Set<Permission> findMenuAssociationPermission(Integer[] menuIds) {
        //查询菜单相关的所有权限
        Set<Permission> permissionSet = new HashSet<>();
        for (Integer menuId : menuIds) {
            //查询单个菜单绑定的权限id
            Integer[] permissionIds = menuDao.findPermissionByMenuId(menuId);
            for (Integer permissionId : permissionIds) {
                //通过单个权限id查询权限
                Permission permission = permissionDao.findPermissionById(permissionId);
                permissionSet.add(permission);
            }
        }
        return permissionSet;
    }
}
